package com.iqiu.cms.web;

import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.conf.PasswordConfig;
import com.ibeetl.admin.core.entity.CoreOrg;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import com.iqiu.cms.baiduai.AiService;
import com.iqiu.cms.service.CorePersonnelService;
import com.iqiu.cms.util.Imagebase64;
import com.iqiu.cms.web.query.CoreUserQuery;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.db.KeyHolder;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.OutputStream;
import java.util.Date;
import java.util.List;

/**
 * 检测人员 接口
 */
@Controller
public class CorePersonnelController {

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/cms/corePersonnel";
    @Autowired
    PasswordConfig.PasswordEncryptService passwordEncryptService;


    @Autowired private CorePersonnelService corePersonnelService;

    @Autowired
    private CorePlatformService platFormService;
    @Autowired
    FileService fileService;
    /* 页面 */

    @GetMapping(MODEL + "/index.do")
    @Function("cms.corePersonnel.query")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("/cms/corePersonnel/index.html") ;
        view.addObject("search", CoreUserQuery.class.getName());
        return view;
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("cms.corePersonnel.edit")
    @ResponseBody
    public ModelAndView edit(Integer id) {
        ModelAndView view = new ModelAndView("/cms/corePersonnel/edit.html");
        CoreUser corePersonnel = corePersonnelService.queryById(id);
        view.addObject("corePersonnel", corePersonnel);
        return view;
    }

    @GetMapping(MODEL + "/add.do")
    @Function("cms.corePersonnel.add")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/cms/corePersonnel/add.html");
        return view;
    }

    /* ajax json */

    @PostMapping(MODEL + "/list.json")
    @Function("cms.corePersonnel.query")
    @ResponseBody
    public JsonResult<PageQuery> list(CoreUserQuery condtion)
    {
        PageQuery page = condtion.getPageQuery();
        corePersonnelService.queryByCondition(page);
        return JsonResult.success(page);
    }

    @PostMapping(MODEL + "/add.json")
    @Function("cms.corePersonnel.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)CoreUser corePersonnel)
    {
        corePersonnel.setDelFlag(0);
        corePersonnel.setUserType(1);
        corePersonnel.setCreateTime(new Date());
        corePersonnel.setCreateUser(platFormService.getCurrentUser().getId().intValue());

        if(StringUtils.isEmpty(corePersonnel.getPassword())) {
            corePersonnel.setPassword(passwordEncryptService.password("123456"));
        }else
            corePersonnel.setPassword(passwordEncryptService.password(corePersonnel.getPassword()));

        String base64img=corePersonnel.getImg();
        if(StringUtils.isNotEmpty(corePersonnel.getImg())){
            FileItem fileItem;
            try {
                CoreUser user = platFormService.getCurrentUser();
                CoreOrg org = platFormService.getCurrentOrg();
                fileItem = fileService.createFileItem("photo.jpg","face", "1", user.getId(), org.getId(), "", null);
            }catch (Exception e){
                fileItem = fileService.createFileItem("photo.jpg", "face", "1", Long.parseLong("1"), Long.parseLong("1"), "", null);
            }
            OutputStream os = fileItem.openOutpuStream();
            Imagebase64.base64StringToImage(corePersonnel.getImg(), os);
            corePersonnel.setImg(fileItem.getId().toString());
        }
        KeyHolder keyHolder =new KeyHolder();
        corePersonnelService.insert(corePersonnel,keyHolder);
        if(StringUtils.isNotEmpty(base64img)) {
            String msg=AiService.add(base64img, corePersonnel.getUserName(),keyHolder.getKey().toString());
            if(!"SUCCESS".equals(msg)){
                CoreUser c=new CoreUser();
                c.setId(Long.parseLong(keyHolder.getKey().toString()));
                c.setImg("0");
                corePersonnelService.updateTemplate(c);
                return new JsonResult().failMessage("人脸上传失败,"+msg);
            }
        }
        return new JsonResult().success();
    }

    @PostMapping(MODEL + "/edit.json")
    @Function("cms.corePersonnel.edit")
    @ResponseBody
    public JsonResult<String> update( CoreUser corePersonnel) {
        corePersonnel.setUserType(1);
        if(StringUtils.isNotEmpty(corePersonnel.getPassword()))
            corePersonnel.setPassword(passwordEncryptService.password(corePersonnel.getPassword()));
        if(StringUtils.isNotEmpty(corePersonnel.getImg())){
            FileItem fileItem;
            try {
                CoreUser user = platFormService.getCurrentUser();
                CoreOrg org = platFormService.getCurrentOrg();
                fileItem = fileService.createFileItem("photo.jpg","face", "1", user.getId(), org.getId(), "", null);
            }catch (Exception e){
                fileItem = fileService.createFileItem("photo.jpg", "face", "1", Long.parseLong("1"), Long.parseLong("1"), "", null);
            }
            OutputStream os = fileItem.openOutpuStream();
            Imagebase64.base64StringToImage(corePersonnel.getImg(), os);

            CoreUser c=corePersonnelService.queryById(corePersonnel.getId());
            String msg="";
            if(StringUtils.isNotEmpty(c.getImg()) && !"0".equals(c.getImg())) {
                msg = AiService.update(corePersonnel.getImg(), corePersonnel.getUserName(), corePersonnel.getId().toString());
            }else{
                msg = AiService.add(corePersonnel.getImg(), corePersonnel.getUserName(), corePersonnel.getId().toString());
            }
            if(!"SUCCESS".equals(msg)){
                return new JsonResult().failMessage("人脸上传失败,"+msg);
            }
            corePersonnel.setImg(fileItem.getId().toString());
        }
        boolean success = corePersonnelService.updateTemplate(corePersonnel);
        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }


   
    @GetMapping(MODEL + "/view.json")
    @Function("cms.corePersonnel.query")
    @ResponseBody
    public JsonResult<CoreUser>queryInfo(Integer id) {
        CoreUser corePersonnel = corePersonnelService.queryById( id);
        return  JsonResult.success(corePersonnel);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function("cms.corePersonnel.delete")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        corePersonnelService.batchDelCoreUser(idList);
        return new JsonResult().success();
    }
    

}
